package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import com.sun.xml.internal.bind.v2.TODO
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.ParseException
import java.text.SimpleDateFormat

/**
 * 应急停水
 类型:
 add新增/新建
 delay延迟
 end 修复/结束
 （应急停水事件类型：
 add新事件/扩大、delay延迟、end修复/结束）
 */
class apiEmergentSync implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiEmergentSync.class)

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        //封装返回报文对象
        JSONObject resultJson = new JSONObject();

        //获取开始时间戳
        long startTime = System.currentTimeMillis();

        //获取入参报文
        String jsonBody = Util.getRequestBody(request, 'utf-8');
        log.debug("入参报文：" + jsonBody);
        String syncType = "";
        //生成应急事件编号
        SimpleDateFormat sm = new SimpleDateFormat("yyyyMMddHHmm");
        String nowDate = sm.format(new Date());
        String record_id = "EM" + nowDate;
        JSONArray resultArr = new JSONArray();
        // 获取短信模板
        //String smsContent = "";
        Integer impactFlag = 0;//影响用户数量标记
        Integer DNxxxCount = 0;//管径大小标记
        String eventReportUnits = "";
        String smsGuid = "";
        String sms_guid = "";
        try {
            //将获取到的请求报文封装为json对象
            JSONObject inPostJson = JSONObject.fromObject(jsonBody);

            //生成rec_guid
            String recGuid = UUID.randomUUID().toString().toUpperCase();

            // 解析参数信息
            String wateroffsmsguid = inPostJson.getString("wateroffsmsguid");

            /*String area_type = KHUtil.GetSFJV(inPostJson, "area_type");
            String event_report_unit = KHUtil.GetSFJV(inPostJson, "event_report_unit");
            String water_station = KHUtil.GetSFJV(inPostJson, "water_station");
            String occurrence_time = KHUtil.GetSFJV(inPostJson, "occurrence_time");
            String fault_type = KHUtil.GetSFJV(inPostJson, "fault_type");
            log.debug("fault_type:" + fault_type);
            String water_pipe = KHUtil.GetSFJV(inPostJson, "water_pipe");
            String event_reason = KHUtil.GetSFJV(inPostJson, "event_reason");
            String event_address = KHUtil.GetSFJV(inPostJson, "event_address");
            String DNxxx = KHUtil.GetSFJV(inPostJson, "DNxxx");
            String effect_scope = KHUtil.GetSFJV(inPostJson, "effect_scope");
            String company_num = KHUtil.GetSFJV(inPostJson, "company_num");
            String resident_num = KHUtil.GetSFJV(inPostJson, "resident_num");
            JSONArray effect_user_detail = inPostJson.getJSONArray("effect_user_detail");
            String impact_traffic = KHUtil.GetSFJV(inPostJson, "impact_traffic");
            syncType = KHUtil.GetSFJV(inPostJson, "sync_type");
            String wateroffchangereason = KHUtil.GetSFJV(inPostJson, "wateroffchangereason");
            String waterontime1 = KHUtil.GetSFJV(inPostJson, "waterontime1");
            String waterontime2 = KHUtil.GetSFJV(inPostJson, "waterontime2");
            String site_contact_tel = KHUtil.GetSFJV(inPostJson, "site_contact_tel");
            String expand = KHUtil.GetSFJV(inPostJson, "expand");*/

            String area_type = inPostJson.getString("area_type");
            String event_report_unit = inPostJson.getString("event_report_unit");
            String water_station = inPostJson.getString("water_station");
            String occurrence_time = inPostJson.getString("occurrence_time");
            String fault_type = inPostJson.getString("fault_type");
            log.debug("fault_type:" + fault_type);
            String water_pipe = inPostJson.getString("water_pipe");
            String event_reason = inPostJson.getString("event_reason");
            String event_address = inPostJson.getString("event_address");
            String DNxxx = inPostJson.getString("dnxxx");
            String effect_scope = inPostJson.getString("effect_scope");
            String company_num = inPostJson.getString("company_num");
            String resident_num = inPostJson.getString("resident_num");
            JSONArray effect_user_detail = inPostJson.getJSONArray("effect_user_detail");
            String impact_traffic = inPostJson.getString("impact_traffic");
            syncType = inPostJson.getString("sync_type");
            String wateroffchangereason = inPostJson.getString("wateroffchangereason");
            String waterontime1 = inPostJson.getString("waterontime1");
            String waterontime2 = inPostJson.getString("waterontime2");
            String site_contact_tel = inPostJson.getString("site_contact_tel");
			String smsContent = inPostJson.getString("smsContent");
            String expand = inPostJson.getString("expand");

            if (KHUtil.isNull("sync_type")) {
                resultJson.put("code", "-2");
                resultJson.put("msg", "调用参数非空校验异常停水类型必填字段;,调用问题处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
            } else {

                // 拼接获取各类调用必填参数信息
                String isCheckNull = "";
                if (syncType.equals("add")) {
                    isCheckNull = KHUtil.isNullMSG("wateroffsmsguid", wateroffsmsguid) + KHUtil.isNullMSG("area_type", area_type) + KHUtil.isNullMSG("event_report_unit", event_report_unit) + KHUtil.isNullMSG("water_station", water_station) + KHUtil.isNullMSG("occurrence_time", occurrence_time) + KHUtil.isNullMSG("fault_type", fault_type) + KHUtil.isNullMSG("water_pipe", water_pipe) + KHUtil.isNullMSG("event_address", event_address) + KHUtil.isNullMSG("effect_scope", effect_scope) + KHUtil.isNullMSG("company_num", company_num) + KHUtil.isNullMSG("resident_num", resident_num) + KHUtil.isNullMSG("impact_traffic", impact_traffic) + KHUtil.isNullMSG("DNxxx", DNxxx);
                } else if (syncType.equals("delay")) {
                    isCheckNull = KHUtil.isNullMSG("wateroffsmsguid", wateroffsmsguid) + KHUtil.isNullMSG("wateroffchangereason", wateroffchangereason) + KHUtil.isNullMSG("waterontime2", waterontime2)
                } else if (syncType.equals("end")) {
                    isCheckNull = KHUtil.isNullMSG("wateroffsmsguid", wateroffsmsguid);
                }

                // 如果必填参数信息不为空说明有为空参数
                if (!KHUtil.isNull(isCheckNull)) {
                    resultJson.put("code", "-2");
                    resultJson.put("msg", "调用参数非空校验异常:" + isCheckNull + "，调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
                } else {

                    String repairTimes = "";
                    if (syncType.equals("delay") && !waterontime1.equals("")) {
                        repairTimes = waterontime1
                    }

                    String getEmergentSyncById = "select count(1) e_con from Swg_Emergentsync where Wateroffsmsguid = '" + wateroffsmsguid + "'";
                    def emergentList = eliteBean.chaxun_sql(getEmergentSyncById, "dataSource");
                    Integer emergentCount = emergentList[0].getAt("e_con");
                    String doMainSQL = "";

                    //查区域ID,传递参数为area_type,找不到默认为集团
                    String Area_guid = '';
                    String SearchAreaSql = " select Area_guid from Group_Area where Area_desc='" + area_type + "' "
                    List SearchAreaList = eliteBean.chaxun_sql(SearchAreaSql, "dataSource");
                    if(SearchAreaList.size()>0){
                        Area_guid = SearchAreaList[0].getAt("Area_guid");
                    }else{
                        Area_guid = '475AE8F5-8C60-0947-96D6-D4999CE07DF4';
                    }

                    //查报告单位,传递参数为event_report_unit,找不到Null
                    String Unit_ID = '';
                    String SearchUnitSql = " select Unit_ID from SW_Failure_report_unit where Unit_DESC='" + event_report_unit + "' "
                    List SearchUnitList = eliteBean.chaxun_sql(SearchUnitSql, "dataSource");
                    if(SearchUnitList.size()>0){
                        Unit_ID = SearchUnitList[0].getAt("Unit_ID");
                    }else{
                        Unit_ID = '';
                    }

                    //查故障类型select Fault_ID from  SW_Fault_type where Fault_DESC=''
                    String Fault_ID = '';
                    String SearchFaultSql = " select Fault_ID from  SW_Fault_type where Fault_DESC='" + fault_type + "' "
                    List SearchFaultList = eliteBean.chaxun_sql(SearchFaultSql, "dataSource");
                    if(SearchFaultList.size()>0){
                        Fault_ID = SearchFaultList[0].getAt("Fault_ID");
                    }else{
                        Fault_ID = '';
                    }

                    //查通知类型
                    String Notice_Area_ID = '';
                    String Notice_Area_desc = '';
                    String SearchNoticeSql = " select Area_id,Area_desc from Water_Notice_Area where Area_type='" + Area_guid + "' "
                    List SearchNoticeList = eliteBean.chaxun_sql(SearchNoticeSql, "dataSource");
                    if(SearchNoticeList.size()>0){
                        Notice_Area_ID = SearchNoticeList[0].getAt("Area_id");
                        Notice_Area_desc = SearchNoticeList[0].getAt("Area_desc");
                    }else{
                        Notice_Area_ID = '';
                    }


                    if (syncType.equals("add") || syncType.equals("delay")) {
                        if (emergentCount == 0) {
                            // 插入主表
                            doMainSQL = '''INSERT INTO Swg_Emergentsync (
														Rec_Guid,
														Wateroffsmsguid,
														Area_Type,
														Event_Report_Unit,
														Water_Station,
														Occurrence_Time,
														Fault_Type,
														Water_Pipe,
														Event_Reason,
														Repair_Time,
														Event_Address,
														Dnxxx,
														Effect_Scope,
														Company_Num,
														Resident_Num,
														Impact_Traffic,
														Sync_Type,
														Site_Contact_Tel,
														Wateroffchangereason,
														Waterontime,
														Createddate,
														Createdby,
														Expand,
														sms_guid,
														record_id
													)
											VALUES
											(
												\'''' + recGuid + '''\',
												\'''' + wateroffsmsguid + '''\',
												\'''' + Area_guid + '''\',
												\'''' + Unit_ID + '''\',
												\'''' + water_station + '''\',
												\'''' + occurrence_time + '''\',
												\'''' + Fault_ID + '''\',
												\'''' + water_pipe + '''\',
												\'''' + event_reason + '''\',
												\'''' + waterontime1 + '''\',
												\'''' + event_address + '''\',
												\'''' + DNxxx + '''\',
												\'''' + effect_scope + '''\',
												\'''' + company_num + '''\',
												\'''' + resident_num + '''\',
												\'''' + impact_traffic + '''\',
												\'''' + syncType + '''\',
												\'''' + site_contact_tel + '''\',
												\'''' + wateroffchangereason + '''\',
												\'''' + waterontime2 + '''\',
												getdate( ),
												\'SELITE\',
												\'''' + expand + '''\',
												\'''' + recGuid + '''\',
                                                \'''' + record_id + '''\' 
											)''';
                        } else if (emergentCount > 0) {
                            doMainSQL = '''update Swg_Emergentsync set Repair_Time = \'''' + waterontime1 + '''\',Wateroffchangereason = \'''' + wateroffchangereason + '''\',Waterontime = \'''' + waterontime2 + '''\' where  Wateroffsmsguid = \'''' + wateroffsmsguid + '''\'''';
                        }

                        int emergentRow = eliteBean.update(doMainSQL.toString(), "dataSource")
                        log.debug("存入emergentSyncInfo表数据：" + emergentRow);


                        //插入应急事件表是否修复字段
                        String repair = "";
                        /*if (syncType == "add") {
                            smsContent = emergentWaterCutOffNotice(occurrence_time, DNxxx, event_address, waterontime1);
                            repair = "A00002";
                        } else if (syncType == "delay") {
                            smsContent = delayedWaterSupplyNotice(repairTimes, wateroffchangereason, event_address, waterontime2);
                            repair = "A00002";
                        } else {
                            repair = "A00001";
                        }*/

                        // 封装用户json报文
                        if (emergentCount == 0) {
                            for (int y = 0; y < effect_user_detail.size(); y++) {
                                //将取出来的用户list值重新赋值给JSONObject
                                JSONObject jsonObj = effect_user_detail.getJSONObject(y);
                                //获取用户编号
                                String userNo = jsonObj.getString("usercode");
                                //获取用户手机号
                                String userTel = jsonObj.getString("ani");

                                //执行数据库操作，将数据存入userInfo表中
                                String userSql = "insert into swg_emergentsync_user(rec_guid,usercode,ani) values('" + recGuid + "','" + userNo + "','" + userTel + "')";
                                int userRow = eliteBean.update(userSql, "dataSource");
                                log.debug("执行到userInfo表数据结果：" + userRow);

                                String doSendSMSSQL = '''Insert Into Documentout
												  (Documentout_Guid,
												   Doctype,
												   Status,
												   Trialcount,
												   Trialcountlimit,
												   Documentpath,
												   Createdby,
												   Createddate,
												   Expectedstartdate,
												   Documentto,
												   Stringfield1,
												   Stringfield2,
												   Sms_Guid,
												   Ucisid)
												Values
												  (\'''' + UUID.randomUUID().toString().toUpperCase() + '''\',
												   3,
												   3,
												   0,
												   5,
												   \'''' + smsContent + '''\',
												   'SELITE',
												   Getdate(),
												   Getdate(),
												   \'''' + userTel + '''\',
												   '应急停水短信',
												   \'''' + recGuid + '''\',
												   \'''' + recGuid + '''\',
												   \'''' + userNo + '''\'
												   )''';
                                int documentOutRow = eliteBean.update(doSendSMSSQL, "dataSource");
                                log.debug("执行到Documentout表数据结果：" + userRow);

                                jsonObj.put("code", 1);
                                resultArr.add(jsonObj);
                            }
                        } else if (emergentCount > 0) {
                            String getSms_guid = "select sms_guid,rec_guid from Swg_Emergentsync where Wateroffsmsguid = '" + wateroffsmsguid + "'";
                            def smsList = eliteBean.chaxun_sql(getSms_guid, "dataSource");
                            sms_guid = smsList[0].getAt("sms_guid");
							recGuid = smsList[0].getAt("rec_guid");
							List getUserList = eliteBean.chaxun_sql("select usercode,ani from swg_emergentsync_user where rec_guid='" + recGuid +"'","dataSource");
							if(getUserList.size() > 0){
								JSONArray userArray = JSONArray.fromObject(getUserList);
								for (int y = 0; y < userArray.size(); y++) {
									//将取出来的用户list值重新赋值给JSONObject
									JSONObject jsonObj = userArray.getJSONObject(y);
									//获取用户编号
									String userNo = jsonObj.getString("usercode");
									//获取用户手机号
									String userTel = jsonObj.getString("ani");

									String doSendSMSSQL = '''Insert Into Documentout
													  (Documentout_Guid,
													   Doctype,
													   Status,
													   Trialcount,
													   Trialcountlimit,
													   Documentpath,
													   Createdby,
													   Createddate,
													   Expectedstartdate,
													   Documentto,
													   Stringfield1,
													   Stringfield2,
													   Sms_Guid,
													   Ucisid)
													Values
													  (\'''' + UUID.randomUUID().toString().toUpperCase() + '''\',
													   3,
													   3,
													   0,
													   5,
													   \'''' + smsContent + '''\',
													   \'SELITE\',
													   Getdate(),
													   Getdate(),
													   \'''' + userTel + '''\',
													   \'应急停水短信\',
													   \'''' + recGuid + '''\',
													   \'''' + sms_guid + '''\',
													   \'''' + userNo + '''\'
													   )''';
									int documentOutRow = eliteBean.update(doSendSMSSQL, "dataSource");

									jsonObj.put("code", 1);
									resultArr.add(jsonObj);
								}
							}
                        }


                        // TODO 应急停水需要插入应急停水事件表
                        String getEmergentSyncRecordId = "select record_id from Swg_Emergentsync where Wateroffsmsguid = '" + wateroffsmsguid + "'";
                        def recordList = eliteBean.chaxun_sql(getEmergentSyncRecordId, "dataSource");
                        String emergentRecordId = recordList[0].getAt("record_id");
                        String getprompt_content_emergencyRecordId = "select count(0) pro_con from prompt_content_emergency where record_id = '" + emergentRecordId + "'";
                        def promptList = eliteBean.chaxun_sql(getprompt_content_emergencyRecordId, "dataSource");
                        Integer promptRecordId = promptList[0].getAt("pro_con");
                        String promptContentEmergency = "";
                        if (promptRecordId == 0) {
                            promptContentEmergency = '''INSERT INTO prompt_content_emergency (
                                                        prompt_guid,
                                                        prompt_matter_id,
                                                        content,
                                                        createdate,
                                                        createby,
                                                        creategroup,
                                                        area_type,
                                                        Contact_time,
                                                        occurrence_time,
                                                        DNxxx,
                                                        fault_type,
                                                        failure_report_unit,
                                                        repair,
                                                        impact,
                                                        repair_time,
                                                        phoneNo,
                                                        impactUser,
                                                        impactAddress,
                                                        record_id,
                                                        modifydate,
                                                        modifyby,
                                                        modifygroup,
                                                        waterpipe,
                                                        inftraffic,
														waterworks
                                                        )
                                                        VALUES
                                                        (
                                                        \'''' + recGuid + '''\',
                                                        \'6FEE80\',
                                                        \'''' + smsContent + '''\',
                                                        getdate(),
                                                        \'SELITE\',
                                                        \'SYSTEM\',
                                                       \'''' + Area_guid + '''\',
                                                        getdate(),
                                                        \'''' + occurrence_time + '''\',
                                                        \'''' + DNxxx + '''\',
                                                        \'''' + Fault_ID + '''\',
                                                        \'''' + Unit_ID + '''\',
                                                        \'''' + repair + '''\',
                                                        \'''' + resident_num + '''\',
                                                        \'''' + waterontime1 + '''\',
                                                        \'''' + site_contact_tel + '''\',
                                                        \'''' + effect_scope + '''\',
                                                        \'''' + event_address + '''\',
                                                        \'''' + record_id + '''\',
                                                        getdate(),
                                                        \'SELITE\',
                                                        \'SYSTEM\',
                                                        \'''' + water_pipe + '''\',
                                                        \'''' + impact_traffic + '''\',
														\'''' + water_station + '''\'
                                                        )''';

                        } else if (promptRecordId > 0) {
                            promptContentEmergency = '''update prompt_content_emergency set 
                                                        content = \'''' + smsContent + '''\',
                                                        repair_time = \'''' + waterontime2 + '''\',
                                                        modifydate = getdate(),
                                                        modifyby = \'SELITE\',
                                                        modifygroup = \'SYSTEM\'
														where record_id = \'''' + emergentRecordId + '''\'
														''';

                        }

                        int promptContentEmergencyRow = eliteBean.update(promptContentEmergency, "dataSource");
                        log.debug("插入应急事件行数：" + promptContentEmergencyRow);
                        log.debug("promptRecordId:" + promptRecordId);
						//调用新建事件接口将应急事件推送致三高
                        String eventName = event_report_unit+water_station+DNxxx+"应急停水";                       
						String getEmergencySql = "select event_report_unit,water_station,dnxxx,event_address,area_type from swg_emergentsync where wateroffsmsguid = '"+wateroffsmsguid+"'";
						List emergencyList = eliteBean.chaxun_sql(getEmergencySql,"dataSource");
						if(emergencyList.size() > 0){
							event_report_unit = emergencyList[0].getAt("event_report_unit");
							water_station = emergencyList[0].getAt("water_station");
							DNxxx = emergencyList[0].getAt("dnxxx");
							event_address = emergencyList[0].getAt("event_address");
							area_type = emergencyList[0].getAt("area_type");
						}
						int traFlag = 0;
						if(impact_traffic.equals("是")){
							traFlag = 1;
						}
                        String createEvent = createNamedEvent(eventName,record_id,event_address,fault_type,smsContent,event_report_unit,site_contact_tel,DNxxx,resident_num,"0",waterontime2,water_station,traFlag,1,eliteBean);
						log.debug(createEvent);
                        if (promptRecordId > 0) {
                            String his_sql = '''insert into prompt_content_emergency_his(prompt_his_guid,prompt_guid,prompt_matter_id,Contact_time,Occurrence_time,DNxxx,Fault_type,Failure_report_unit,repair,impact,repair_time,content,createdate,createby,creategroup,area_type,PhoneNO,ImpactUser,ImpactAddress,record_id,modifydate,modifyby,modifygroup,recordstatus,waterpipe,inftraffic,fieldstate,waterworks,putonrecords,sendsms)
						select newid(),prompt_guid,prompt_matter_id,Contact_time,Occurrence_time,DNxxx,Fault_type,Failure_report_unit,repair,impact,repair_time,content,createdate,createby,creategroup,area_type,PhoneNO,ImpactUser,ImpactAddress,record_id,getdate(),\'SELITE\',\'SYSTEM\',\'修改\',waterpipe,inftraffic,fieldstate,waterworks,putonrecords,sendsms from prompt_content_emergency where record_id=\'''' + emergentRecordId + '''\'
						''';
                            Integer his_row = eliteBean.update(his_sql, "dataSource");
                            log.debug("emergentRecordId:" + emergentRecordId);
                            log.debug("插入历史表扩大停水记录:" + his_row);
                        }
                        // TODO 内部通知
                        if (effect_user_detail.size() < 1000) {
                            impactFlag = 1;
                        } else if (effect_user_detail.size() >= 1000 && effect_user_detail.size() < 5000) {
                            impactFlag = 2;
                        } else if (effect_user_detail.size() >= 5000 && effect_user_detail.size() < 10000) {
                            impactFlag = 3;
                        } else if (effect_user_detail.size() >= 10000 && effect_user_detail.size() < 20000) {
                            impactFlag = 4;
                        } else if (effect_user_detail.size() > 20000) {
                            impactFlag = 5;
                        }

                        if (Integer.parseInt(DNxxx) < 200) {
                            DNxxxCount = 1;
                        } else if (Integer.parseInt(DNxxx) >= 200 && Integer.parseInt(DNxxx) < 800) {
                            DNxxxCount = 2;
                        } else if (Integer.parseInt(DNxxx) >= 800 && Integer.parseInt(DNxxx) < 1200) {
                            DNxxxCount = 3;
                        } else if (Integer.parseInt(DNxxx) >= 1200) {
                            DNxxxCount = 4;
                        }

                        //修改，直接赋值
                        eventReportUnits = Unit_ID;
                    /*弃用
                        if (event_report_unit.equals("罗湖分公司")) {
                            eventReportUnits = "D72224";
                        } else if (event_report_unit.equals("福田分公司")) {
                            eventReportUnits = "CBB85D";
                        } else if (event_report_unit.equals("盐田分公司")) {
                            eventReportUnits = "56C587";
                        } else if (event_report_unit.equals("南山分公司")) {
                            eventReportUnits = "3BCF3E";
                        } else if (event_report_unit.equals("莲塘供水公司")) {
                            eventReportUnits = "1FF39C";
                        } else if (event_report_unit.equals("阀门分公司")) {
                            eventReportUnits = "6ECD9C";
                        } else if (event_report_unit.equals("泵站分公司")) {
                            eventReportUnits = "B2B7BD";
                        } else if (event_report_unit.equals("龙华管网")) {
                            eventReportUnits = "D574D3";
                        } else if (event_report_unit.equals("观澜管网")) {
                            eventReportUnits = "6F239A";
                        } else if (event_report_unit.equals("布龙管网")) {
                            eventReportUnits = "D01831";
                        } else if (event_report_unit.equals("福永水司")) {
                            eventReportUnits = "5FFF27";
                        } else if (event_report_unit.equals("石岩水司")) {
                            eventReportUnits = "4782C3";
                        } else if (event_report_unit.equals("松岗水司")) {
                            eventReportUnits = "E94FCA";
                        } else if (event_report_unit.equals("沙井水司")) {
                            eventReportUnits = "9DEDA5";
                        } else if (event_report_unit.equals("龙城分公司")) {
                            eventReportUnits = "3BA3E0";
                        } else if (event_report_unit.equals("横岗水司")) {
                            eventReportUnits = "7793D1";
                        } else if (event_report_unit.equals("平湖水司")) {
                            eventReportUnits = "420DB9";
                        } else if (event_report_unit.equals("坪山水司")) {
                            eventReportUnits = "E9263D";
                        } else if (event_report_unit.equals("坑梓水司")) {
                            eventReportUnits = "EA043E";
                        } else if (event_report_unit.equals("大鹏新区水司")) {
                            eventReportUnits = "FDFF8C";
                        } else if (event_report_unit.equals("公明南所")) {
                            eventReportUnits = "AB6C91";
                        } else if (event_report_unit.equals("马田所")) {
                            eventReportUnits = "B840A3";
                        } else if (event_report_unit.equals("公明北所")) {
                            eventReportUnits = "5AD263";
                        } else if (event_report_unit.equals("玉塘所")) {
                            eventReportUnits = "E342F0";
                        } else if (event_report_unit.equals("光明所")) {
                            eventReportUnits = "AF8DF6";
                        } else if (event_report_unit.equals("凤凰所")) {
                            eventReportUnits = "2E57DF";
                        } else if (event_report_unit.equals("新湖所")) {
                            eventReportUnits = "C1206C";
                        }
                    弃用*/
                        if (emergentCount == 0) {
                            smsGuid = recGuid;
                        } else if (emergentCount > 0) {
                            smsGuid = sms_guid;
                        }
                        String insideNotices = insideNotice(eventReportUnits, impactFlag, DNxxxCount, water_station, smsContent, recGuid, smsGuid, eliteBean);


                        String promptContentSql = '''INSERT INTO prompt_content ( prompt_guid, prompt_matter_id, content, priority, createby, createdate, creategroup, MODIFY, modifytime, leading_official, area ,area_type)
												VALUES
												( \'''' + UUID.randomUUID().toString().toUpperCase() + '''\', \'02C0D6\', \'''' + smsContent + '''\', \'700C7E\', \'SELITE\', getdate(), \'SYSTEM\', \'SELETE\', getdate(), \'''' + site_contact_tel + '''\', \'''' + Notice_Area_ID + '''\', \'''' + Area_guid + '''\')''';

                        Integer promptContentRow = eliteBean.update(promptContentSql, "dataSource");
                    }


                    if ((syncType.equals("end") || syncType == 'end')) {
                        String getEmergentSyncRecordId = "select record_id from Swg_Emergentsync where Wateroffsmsguid = '" + wateroffsmsguid + "'";
                        def recordList = eliteBean.chaxun_sql(getEmergentSyncRecordId, "dataSource");
                        String emergentRecordId = recordList[0].getAt("record_id");
                        String getprompt_content_emergencyRecordId = "select count(0) pro_con from prompt_content_emergency where record_id = '" + emergentRecordId + "'";
                        def promptList = eliteBean.chaxun_sql(getprompt_content_emergencyRecordId, "dataSource");
                        Integer promptRecordId = promptList[0].getAt("pro_con");
                        if (promptRecordId != null && promptRecordId != "") {
                            String his_sql = '''insert into prompt_content_emergency_his(prompt_his_guid,prompt_guid,prompt_matter_id,Contact_time,Occurrence_time,DNxxx,Fault_type,Failure_report_unit,repair,impact,repair_time,content,createdate,createby,creategroup,area_type,PhoneNO,ImpactUser,ImpactAddress,record_id,modifydate,modifyby,modifygroup,recordstatus,waterpipe,inftraffic,fieldstate,waterworks,putonrecords,sendsms)
							select newid(),prompt_guid,prompt_matter_id,Contact_time,Occurrence_time,DNxxx,Fault_type,Failure_report_unit,repair,impact,repair_time,content,createdate,createby,creategroup,area_type,PhoneNO,ImpactUser,ImpactAddress,record_id,getdate(),\'SELITE\',\'SYSTEM\',\'删除\',waterpipe,inftraffic,fieldstate,waterworks,putonrecords,sendsms from prompt_content_emergency where record_id=\'''' + emergentRecordId + '''\'
							''';
                            Integer his_row = eliteBean.update(his_sql, "dataSource");
                            String deleteEmergentSql = "delete from prompt_content_emergency where record_id = '" + emergentRecordId + "'";
                            Integer deleteEmergentRow = eliteBean.update(deleteEmergentSql, "dataSource");
                            String deleteEmergentSqls = "delete from Swg_Emergentsync where Wateroffsmsguid = '" + wateroffsmsguid + "'";
                            Integer deleteEmergentRows = eliteBean.update(deleteEmergentSqls, "dataSource");
                            log.debug("删除应急事件表数据:" + deleteEmergentRow);
                            log.debug("删除应急停水主表数据:" + deleteEmergentRow);
                        }

                    }

                    resultJson.put("code", "1");
                    resultJson.put("msg", "批次号:" + wateroffsmsguid + " Succ处理成功、调用问题处理时长(毫秒):" + (System.currentTimeMillis() - startTime).toString());
                    resultJson.put("data", resultArr);
                }

            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            resultJson.put("code", "-2");
            resultJson.put("msg", "Exception:可能是JSON格式问题、连接数据库问题、调用问题处理时长(毫秒):" + (System.currentTimeMillis() - startTime).toString());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "智慧停水[应急]", "apiEmergentSync", jsonBody, resultJson.toString(), (System.currentTimeMillis() - startTime).toString(), syncType);
        }

        log.debug("数据接入处理完成返回结果:" + resultJson.toString());
        return resultJson.toString();
    }

    /**
     * 应急停水通知
     * @param occurrenceTime 发生时间
     * @param DNxxx 管径大小
     * @param eventAddress 地址信息
     * @return sb 短信报文
     * @throws ParseException
     */
    public String emergentWaterCutOffNotice(String occurrenceTime, String DNxxx, String eventAddress, String repairTime) throws ParseException {
        Date date = new SimpleDateFormat("yyyy-MM-ddHH").parse(occurrenceTime);
        String now = new SimpleDateFormat("yyyy年MM月dd日HH时").format(date);
        Date dateOne = new SimpleDateFormat("yyyy-MM-ddHH").parse(repairTime);
        String repairTimeTwo = new SimpleDateFormat("dd日HH时").format(dateOne);
        StringBuffer sb = new StringBuffer()
        sb.append("尊敬的客户，" + now + "，因" + eventAddress)
        sb.append("小区有一" + DNxxx + "供水管（出厂水管、原水管）爆管/漏水/渗漏或")
        sb.append("阀门故障，需紧急停水抢修，预计" + repairTimeTwo + "修复/修复时间待")
        sb.append("定。我司将全力抢修，给您带来不便，敬请谅解。恢复供水后，")
        sb.append("可能出现短暂水质波动，建议适当排放后使用。【深圳水务集团】")
        return sb.toString()
    }

    /**
     *
     * @param repairTime 原定解决时间
     * @param eventDesc 延迟原因
     * @param eventAddress 地址信息
     * @param delayedTime 延迟时间
     * @return sb 短信报文
     */
    public String delayedWaterSupplyNotice(String repairTime, String eventDesc, String eventAddress, String delayedTime) throws ParseException {
        //原定时间
        Date date = new SimpleDateFormat("yyyy-MM-ddHH").parse(repairTime)
        String now = new SimpleDateFormat("yyyy年MM月dd日HH时").format(date)
        //延迟时间
        Date date1 = new SimpleDateFormat("yyyy-MM-ddHH").parse(delayedTime)
        String now1 = new SimpleDateFormat("yyyy年MM月dd日HH时").format(date1)
        StringBuffer sb = new StringBuffer()
        sb.append("尊敬的客户，原定于" + now + "恢复供水的" + eventAddress + "的管道/阀门故障抢修，")
        sb.append("因" + eventDesc + "（例如：现场施工难度大）需延迟至" + now1 + "恢复供水。不便之处，敬请谅解! 【深圳水务集团】")
        return sb.toString()
    }

    /**
     * 内部通知
     * @param insideFailureReportUnit 报告单位
     * @param impact 影响户数
     * @param DNxxxCount 管径大小
     * @param waterWorks 所属水务所
     * @return
     */
    public String insideNotice(String insideFailureReportUnit, Integer impact, Integer DNxxxCount, String waterWorks, String smsContent, String recGuid, String sms_guid, EliteBean eliteBean) {
          String noticeSql = "select type_id from org_jobtitletype where Failure_report_unit like '%" + insideFailureReportUnit + "%' and impact like '%" + impact + "%' and DNxxx like '%" + DNxxxCount + "%' and waterworks like '%" + waterWorks + "%' ";
        List noticeList = eliteBean.chaxun_sql(noticeSql, "dataSource");
        log.debug("节点集合：" + noticeList.size());
        if (noticeList != null && noticeList.size() != 0) {
            //获取节点id
            for (int y = 0; y < noticeList.size(); y++) {
                String TypeId = noticeList[y].getAt("type_id");
                //获取内部通知的手机号码
                String mobileSql = '''SELECT
                                    os.mobile,os.userid 
                                  FROM
                                    org_staffinfo os
                                    LEFT JOIN org_jobtitle oj ON os.jobtitle  = oj.jobtitle_id
                                    LEFT JOIN org_groupuser ogu ON ogu.userid= os.userid 
                                  WHERE
                                    ogu.group_id = \'''' + TypeId + '''\'
                                  ORDER BY
                                    dsporder''';
                List mobileList = eliteBean.chaxun_sql(mobileSql, "dataSource");
                JSONArray jsonArray = JSONArray.fromObject(mobileList);
                String sms_guids = UUID.randomUUID().toString().toUpperCase();
                String smsContents = "【客户联络中心】";
                smsContent += smsContents;
                for (int x = 0; x < mobileList.size(); x++) {
                    //将取出来的用户list值重新赋值给JSONObject
                    JSONObject tempJson = jsonArray.getJSONObject(x);
                    //获取用户手机号
                    String userTel = tempJson.getString("mobile");
                    //获取用户编号
                    //String userNo = tempJson.getString("userid");
                    String doSendSMSSQL = '''Insert Into Documentout
												  (Documentout_Guid,
												   Doctype,
												   Status,
												   Trialcount,
												   Trialcountlimit,
												   Documentpath,
												   Createdby,
												   Createddate,
												   Expectedstartdate,
												   Documentto,
												   Stringfield1,
												   Stringfield2,
												   Sms_Guid,
												   template_id)
												Values
												  (\'''' + UUID.randomUUID().toString().toUpperCase() + '''\',
												   3,
												   3,
												   0,
												   5,
												   \'''' + smsContent + '''\',
												   'SELITE',
												   Getdate(),
												   Getdate(),
												   \'''' + userTel + '''\',
												   '智慧停水发送',
												   \'''' + recGuid + '''\',
												   \'''' + sms_guids + '''\',
												   \'''' + TypeId + '''\'
												   )''';
                    int documentOutRow = eliteBean.update(doSendSMSSQL, "dataSource");
                    log.debug("执行到Documentout表数据结果：" + documentOutRow);
                }
                String sendListSql = '''INSERT INTO ITSV.szwaterDB.DBO.sendlist ( content, sendtime, schtime, smscount, subcode, bh, status, server, depid, isread, typework, loginname )
                        select 
                        documentpath,
                        getdate(),
                        getdate(),
                        1,
                        1,
                        documentout_guid,
                        0,
                        1,
                        1,
                        0,
                        15,
                        'linzm' from documentout where sms_guid = \'''' + sms_guids + '''\'
                    ''';
                int sendListRow = eliteBean.update(sendListSql, "dataSource");
                log.debug("执行到ITSV.szwaterDB.DBO.sendlist表数据结果：" + sendListRow);

                String mobileTempSql = '''INSERT INTO ITSV.szwaterDB.DBO.mobiletemp_1 ( realname, mobile, loginname, bh )
                                        select 
                                        '',
                                        documentto,
                                        '',
                                        documentout_guid from documentout where sms_guid = \'''' + sms_guids + '''\'
                                    ''';
                int mobileTempRow = eliteBean.update(sendListSql, "dataSource");
                log.debug("执行到ITSV.szwaterDB.DBO.mobiletemp_1表数据结果：" + mobileTempRow);

                log.debug("内部通知手机号：" + mobileList);
            }
        }
    }

    /**
     * 新建事件接口
     * @param eventName 事件名称
     * @param eventCatalog 事件类型 2：应急事件 3：停水通知
     * @param happenedAddress 事件发生地址
     * @param operator 操作员
     * @param description 事件描述
     * @param currentOperator 当前操作员
     * @return
     */
	 /*
	 {
    "eventName": R.temp.eventname,
    "eventCatalog": 2,
    "happenedAddress": R.temp.impactaddress_a,
    "operator": 2,
    "description": R.temp.description,
    "currentOperator": 2,
    "CrmEventID": R.temp.em_id,
    "FaultType": R.temp.fault_type_desc,
    "FaultUnit": R.temp.failure_report_unit_desc,
    "ConnectPhone": R.temp.sw_phoneno_a,
    "Caliber": R.temp.sw_dnxxx_a,
    "AffectPeople": R.temp.impact_a,
    "IsRepaire": R.temp.repair_flag,
    "RepaireTime": R.temp.sw_repair_time_a,
    "Organization": R.temp.waterworks_a,
    "AffectTraffic": R.temp.inftraffic_flag,
    "SendMessage": R.temp.sms_flag
}

	 */
    public String createNamedEvent(String eventName,String CrmEventID,String happenedAddress,
                                   String FaultType,String description,String FaultUnit,String ConnectPhone,String Caliber,String AffectPeople,String IsRepaire,String RepaireTime,String Organization,int AffectTraffic,int SendMessage, EliteBean eliteBean){
        //获取请求接口URL
        String httpUrl = KHDBConfig.getAPIURL(eliteBean, "createdNamedEvent");
		log.debug("新建事件接口地址:" + httpUrl);
        //接口调用
		long startTimes = System.currentTimeMillis();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("eventName",eventName);
        jsonObject.put("eventCatalog",2);
        jsonObject.put("happenedAddress",happenedAddress);
        jsonObject.put("operator","2009");
        jsonObject.put("description",description);
        jsonObject.put("currentOperator","2009");
		jsonObject.put("CrmEventID",CrmEventID);
		jsonObject.put("FaultType",FaultType);
		jsonObject.put("FaultUnit",FaultUnit);
		jsonObject.put("ConnectPhone",ConnectPhone);
		jsonObject.put("Caliber",Caliber);
		jsonObject.put("AffectPeople",AffectPeople);
		jsonObject.put("IsRepaire",IsRepaire);
		jsonObject.put("RepaireTime",RepaireTime);
		jsonObject.put("Organization",Organization);
		jsonObject.put("AffectTraffic",AffectTraffic);
		jsonObject.put("SendMessage",SendMessage);
		log.debug("新建事件请求报文:" + jsonObject.toString());
        Map<String, String> headMap = new HashMap<String, String>();
		headMap.put("Content-Type", "application/json");
        String doPostResult = Util.doHttpPostUseHead(httpUrl, jsonObject.toString(), "UTF-8", 120000, 0, headMap);
        log.debug("新建事假接口返回:" + doPostResult);
		long endTimes = System.currentTimeMillis();
		long hs = endTimes - startTimes;
		eliteBean.update("insert into ws_interface_log (log_guid,Name,Time,Type,Request,Response,Consume) values (NEWID(),'三高新建事件接口',GETDATE(),'"+httpUrl+"','"+jsonObject.toString()+"','"+doPostResult+"',"+hs+")","dataSource");
        return doPostResult;

    }
}
